package com.dr.app.test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * @ProjectName: spring
 * @Package: com.dr.app.test
 * @Description: java类作用描述
 * @Author: duanrui
 * @CreateDate: 2021/8/31 20:26
 * @Version: 1.0
 * <p>
 * Copyright: Copyright (c) 2021
 */
public class AlternatelyPrint {
	//	static Thread threadA, threadB, threadC;
	//以A开始的信号量,初始信号量数量为1
	private static Semaphore A = new Semaphore(1);
	//B、C信号量,A完成后开始,初始信号数量为0
	private static Semaphore B = new Semaphore(0);
	private static Semaphore C = new Semaphore(0);


	public static void main(String[] args) {
//		threadA = new Thread(() -> {
//			for (int i = 0; i < 10; i++) {
//				// 打印当前线程名称
//				System.out.print(Thread.currentThread().getName());
//				// 唤醒下一个线程
//				LockSupport.unpark(threadB);
//				// 当前线程阻塞
//				LockSupport.park();
//			}
//		}, "A");
//		threadB = new Thread(() -> {
//			for (int i = 0; i < 10; i++) {
//				// 先阻塞等待被唤醒
//				LockSupport.park();
//				System.out.print(Thread.currentThread().getName());
//				// 唤醒下一个线程
//				LockSupport.unpark(threadC);
//			}
//		}, "B");
//		threadC = new Thread(() -> {
//			for (int i = 0; i < 10; i++) {
//				// 先阻塞等待被唤醒
//				LockSupport.park();
//				System.out.print(Thread.currentThread().getName());
//				// 唤醒下一个线程
//				LockSupport.unpark(threadA);
//			}
//		}, "C");
//		threadA.start();
//		threadB.start();
//		threadC.start();


		new Thread(() -> {
			try {
				for (int i = 0; i < 10; i++) {

					A.acquire();
					// 打印当前线程名称
					System.out.print(Thread.currentThread().getName());
					B.release();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}, "A").start();
		new Thread(() -> {
			try {
				for (int i = 0; i < 10; i++) {
					B.acquire();
					// 打印当前线程名称
					System.out.print(Thread.currentThread().getName());
					C.release();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "B").start();
		new Thread(() -> {
			try {
				for (int i = 0; i < 10; i++) {
					C.acquire();
					// 打印当前线程名称
					System.out.print(Thread.currentThread().getName());
					A.release();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "C").start();
	}


}
